package com.utils;


import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author: xiaomi
 * @date: 2020/12/23
 * @description: 包名替换工具
 */
public class PackageNameReplaceUtils {


    public static void main(String[] args) {
        strategy4RemoveImport("D:\\Projects\\IdeaProjects\\DataStructureResearch\\src\\main\\java\\com\\sourcetrip",
                "com.sourcetrip.","hashmap");
    }
    /**
     * 针对文件夹下的 .java 文件，移除 import 一行，并且修复包名
     *
     * @param path
     */
    static void strategy4RemoveImport(String path, String preStr, String lastPackageName) {
        File file = new File(path);
        if (!file.isDirectory()) {
            return;
        }
        File[] files = file.listFiles();
        for (File f :
                files) {
            if (f.getName().endsWith(".java")) {
                String content = readContent(f);
                String replacementStr = replaceProcess(content, preStr + lastPackageName + ".");
                writeContent(replacementStr,f);
            }
        }
    }

    static String readContent(File file) {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)))) {
            String lineTxt = null;
            while ((lineTxt = bufferedReader.readLine()) != null) {
                sb.append(lineTxt);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            return sb.toString();
        }
    }

    static void writeContent(String content, File file){
        try (FileOutputStream fileOutputStream = new FileOutputStream(file)){
            fileOutputStream.write(content.getBytes());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    static String replaceProcess(String content, String packageName) {
        Pattern pattern = Pattern.compile("package (\\S+);");
        Matcher matcher = pattern.matcher(content);
        String oldValue = "";
        if (matcher.find()) {
            String str = matcher.group(1);
            oldValue = matcher.group();
        }
        String replacement = "package " + packageName + ";";
        String newStr = content.replace(oldValue, replacement);
        //接着删除 import
        newStr=newStr.replaceAll("import \\S+;","");
        return newStr;
    }
}
